﻿using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.List;
using Kingdee.BOS.Core.List.PlugIn;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WSDZ.KM.ZH.XiaoManIntegrating40
{
    [Description("【物料列表】物料推送小满"), HotUpdate]
    public class MatPushXM_List : AbstractListPlugIn
    {
        public string btype = "物料推送小满";
        /// <summary>
        /// 日志文件路径
        /// </summary>
        public string logType = "物料推送小满";
        public TokenData TokenObj = null;
        public string url { get; set; } = "https://api-sandbox.xiaoman.cn/v1/product/push";
        public override void AfterBarItemClick(AfterBarItemClickEventArgs e)
        {
            base.AfterBarItemClick(e);
            //推送小满
            if (e.BarItemKey.EqualsV1("btnPushXM"))
            {
                try
                {
                    var lv = this.View as IListView;
                    if (lv == null)
                        return;
                    var selectedRows = lv.SelectedRowsInfo;
                    if (selectedRows == null || selectedRows.Count == 0)
                    {
                        this.View.ShowMessage("当前没有行被选中！");
                        return;
                    }
                    List<int> ids = selectedRows.Select(x => x.PrimaryKeyValue.ToStringV1().ToInt32V1()).Where(x=>x!=0).Distinct().ToList();
                    if (ids!=null&&ids.Count>0)
                        Push(Context,ids);
                }
                catch (Exception ex)
                {
                    View.ShowErrMessage(ex.Message);
                    return;
                }
            }
        }

        public void Push(Context ctx,List<int> idList,bool isTaskTimer=false)
        {
            List<Mat> matList = new List<Mat>();
            List<MatMsgInfo> msgList = new List<MatMsgInfo>();
            int size = 1000;
            int allCount = idList.Count <= size ? 1 : idList.Count % size > 0 ? idList.Count / size + 1 : idList.Count / size;
            for (int i = 0; i < allCount; i++)
            {
                List<int> ids = idList.Skip(i * size).Take(size).ToList();
                string sql = $@"select
matId=mat.FMATERIALID
,xmId=mat.FXMID  --小满ID
,matNumber=mat.FNUMBER
,matName=matL.FNAME
,matModel=matL.FSpecification --规格型号
,unitNumber='Piece'
,matDescription=matL.Fdescription --描述
from T_BD_MATERIAL mat 
left join T_BD_MATERIAL_L matL on mat.FMATERIALID=matL.FMATERIALID and matL.FLOCALEID=2052
where mat.FDOCUMENTSTATUS='C' and mat.FMATERIALID  in ({string.Join(",", ids)})";
                DynamicObjectCollection datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (datas!=null&&datas.Count>0)
                {
                    List<Mat> matdata = datas.DynamicObjectCollectionToDataList<Mat>();
                    matList.AddRange(matdata);
                }
            }
            if (matList==null||matList.Count<1)
            {
                View.ShowErrMessage("不存在可推送数据!!!");
                return;
            }
            var tokens = PostHelper.GetToken(logType);
            if (!tokens.Item1)
            {
                LogHelper.XiaoManLog($"【获取token错误】【msg:{tokens.Item2.msg}】", logType);
                return;
            }
            TokenObj = tokens.Item2;
            Dictionary<string, string> headers = new Dictionary<string, string>();
            headers.Add("Authorization", $@"Bearer {TokenObj.token}");
            foreach (Mat matObj in matList)
            {
                bool isAdd = matObj.xmId.IsNullOrEmptyOrWhiteSpace();
                try
                {
                    string json = string.Empty;
                    {
                        JObject MainObj = new JObject();
                        if (!isAdd)
                            MainObj["product_id"] = matObj.xmId;
                        MainObj["product_no"] = matObj.matNumber;
                        MainObj["name"] = matObj.matName;
                        string modelStr = matObj.matModel.Length > 64 ? matObj.matModel.Substring(0, 64) : matObj.matModel;
                        MainObj["model"] = modelStr;
                        MainObj["unit"] = matObj.unitNumber;
                        MainObj["description"] = matObj.matDescription;
                        json = MainObj.ToStringV1();
                    }
                    string inContent = $"【物料推送小满】【调用接口】【物料ID:{matObj.matId}  物料编码:{matObj.matNumber}】\n【地址：{url}】\n【header:{JsonConvert.SerializeObject(headers)}】\n【传入内容：{json}】";
                    LogHelper.XiaoManLog(inContent, logType);
                    string reponse = PostHelper.Post(url, json, headers);
                    string outContent = $"【物料推送小满】【接口返回】【物料ID:{matObj.matId}  物料编码:{matObj.matNumber}】\n【地址：{url}】\n【header:{JsonConvert.SerializeObject(headers)}】\n【返回内容：{reponse}】";
                    LogHelper.XiaoManLog(outContent, logType);
                    //解析返回数据
                    JObject reObj = JsonConvert.DeserializeObject<JObject>(reponse);
                    if (reObj["code"].ToStringV1().EqualsV1("200") && reObj["message"].ToStringV1().EqualsV1("success"))
                    {
                        //推送物料成功
                        if (isAdd)
                        {
                            JObject dataObj = JsonConvert.DeserializeObject<JObject>(reObj["data"].ToStringV1());
                            string xmid = dataObj["product_id"].ToStringV1();
                            DBUtils.Execute(ctx, $@"update T_BD_MATERIAL set FXMID='{xmid}' where FMATERIALID={matObj.matId}");
                        }
                        msgList.Add(new MatMsgInfo (){status=true,number=matObj.matNumber });
                    }
                    else
                        msgList.Add(new MatMsgInfo() { status = false, number = matObj.matNumber, msg = reObj["message"].ToStringV1() });
                }
                catch (Exception ex)
                {
                    LogHelper.XiaoManLog($"【异常】【MAT1001】【物料ID:{matObj.matId}】【物料编码:{matObj.matNumber}】【msg:{ex.Message}】", logType);
                    msgList.Add(new MatMsgInfo() { status = false, number = matObj.matNumber, msg = $@"【异常MAT1001】{ex.Message}" });
                    continue;
                }
            }
            if (!isTaskTimer)
            {
                string rMsg = string.Empty;
                List<MatMsgInfo> tList = msgList.Where(x => x.status).ToList();
                List<MatMsgInfo> fList = msgList.Where(x => !x.status).ToList();
                rMsg = $"推送完成,成功条数{tList.Count}\n";
                if (fList.Count > 0)
                {
                    List<string> eList = fList.Select(x => $@"物料{x.number}推送失败,{x.msg}").ToList();
                    rMsg += $"失败条数{fList.Count}\n{string.Join("\n", eList)}";
                }
                View.ShowMessage(rMsg);
                View.Refresh();
            }
        
        }

    }
    public class MatMsgInfo
    {
        public bool status { get; set; }
        public string number { get; set; }
        public string msg { get; set; }
    }
}
